
from rest_framework import exceptions
from rest_framework.authentication import BaseAuthentication
import datetime
import time
# 用drf的认证,写一个类,可以继承BaseAuthentication,也可以不用
from UserProfile import models
from Blog.util import DataFailed

class LoginAuth(BaseAuthentication):
    # 函数名一定要叫authenticate,接收必须两个参数,第二个参数是request对象
    def authenticate(self, request):
        # 从request对象中取出token(也可以从其它地方取)
        try:
            # token = request.COOKIES.get("token")
            token = request.META.get('HTTP_AUTHORIZATION',None)
            if token == None:
                raise DataFailed({"status":110,"msg":"您还未登录"})
            if token == "":
                raise DataFailed({"status": 110, "msg": "您还未登录"})
        # 去数据库过滤,查询
            ret = models.User.objects.filter(token=token).values('email','id','username','last_login')
            if ret[0]['last_login'] is None:
                raise Exception()
            # last_datetime =  ret[0]['last_login'].strftime('%Y-%m-%d %H:%M:%S')
            now_time = time.time()
            last_datetime = time.strptime(ret[0]['last_login'].strftime('%Y-%m-%d %H:%M:%S'), "%Y-%m-%d %H:%M:%S")
            last_login = int(time.mktime(last_datetime))
            date_line = last_login + 60*60*3
            print(last_login)
            print(date_line)
            print(now_time)
            if now_time>date_line:
                raise  DataFailed()
            return (ret,token)
        except DataFailed as e:
            raise  DataFailed({"status":110,"msg":"登录已过期"})
        except Exception as e:
            print(e)
            raise DataFailed({"status":110,"msg":"您还未登录"})

##不需要用到认证： authentication_classes = [ ]


